import { Button, Card, Avatar, Statistic, List, Modal, Form, Input, message } from 'antd';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getMe, updateProfile, changePassword, getMyCourses, getAppliedCourses } from '../../api/teacher';
import { Teacher } from '../../types';
import { UserOutlined, EditOutlined, LogoutOutlined, SafetyOutlined, RightOutlined, BookOutlined, FileTextOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

export default function MyProfile() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { data: me, isLoading } = useQuery({ 
    queryKey: ['teacher', 'me'], 
    queryFn: getMe,
    retry: false,
  });
  
  // 获取当前课程列表
  const { data: myCourses = [] } = useQuery({
    queryKey: ['teacher', 'courses'],
    queryFn: getMyCourses,
    retry: false,
  });
  
  // 获取申请中的课程列表
  const { data: appliedCourses = [] } = useQuery({
    queryKey: ['teacher', 'applied-courses'],
    queryFn: getAppliedCourses,
    retry: false,
  });
  
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  const updateProfileMutation = useMutation({
    mutationFn: updateProfile,
    onSuccess: (data) => {
      queryClient.setQueryData(['teacher', 'me'], data);
      message.success('个人信息更新成功');
      setIsEditModalOpen(false);
      form.resetFields();
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  const changePasswordMutation = useMutation({
    mutationFn: changePassword,
    onSuccess: () => {
      message.success('密码修改成功');
      setIsPasswordModalOpen(false);
      passwordForm.resetFields();
    },
    onError: (error: any) => {
      message.error(error.message || '密码修改失败，请检查旧密码是否正确');
    },
  });

  const handleEdit = () => {
    if (me) {
      form.setFieldsValue({
        name: me.name,
        email: me.email || '',
        phone: me.phone || '',
        college: me.college || '',
        account: me.account || '',
        title: me.title || '',
        researchArea: me.researchArea || '',
      });
      setIsEditModalOpen(true);
    } else {
      message.warning('个人信息加载中，请稍候');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // 只提交可编辑的字段：姓名、邮箱、电话、职称、研究方向
      // 所属学院和工号不允许修改
      const updateData: Partial<Teacher> = {
        name: values.name,
        title: values.title,
      };
      
      // 可选字段，只有当有值时才添加
      if (values.email) {
        updateData.email = values.email;
      }
      if (values.phone) {
        updateData.phone = values.phone;
      }
      if (values.researchArea !== undefined) {
        updateData.researchArea = values.researchArea || undefined;
      }
      
      updateProfileMutation.mutate(updateData);
    } catch (error) {
      console.error('表单验证失败:', error);
      message.error('请检查表单输入是否正确');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('role');
    localStorage.removeItem('dev_mode');
    navigate('/login');
  };

  return (
    <div className="space-y-6 pb-20">
      {/* 个人信息 */}
      <div className="text-xl font-semibold text-gray-800 mb-4">个人信息</div>
      
      <Card className="shadow-md" bordered={false}>
        {/* 头像和基本信息 */}
        <div className="flex items-center gap-5 mb-6">
          <Avatar 
            size={72} 
            icon={<UserOutlined />} 
            className="flex-shrink-0"
            style={{ 
              background: '#f2f6ff',
              color: '#1890ff',
              fontSize: '32px'
            }} 
          />
          <div className="flex-1">
            <div className="flex items-center gap-3 flex-wrap mb-3">
              <div className="text-xl font-semibold text-gray-800">{me?.name || '教师'}</div>
              <span className="px-3 py-1 bg-blue-50 text-blue-600 border border-blue-200 rounded-full text-xs font-medium">
                教师
              </span>
              {me?.college && (
                <span className="px-3 py-1 bg-green-50 text-green-600 border border-green-200 rounded-full text-xs font-medium">
                  {me.college}
                </span>
              )}
            </div>
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={handleEdit}
              style={{ 
                background: '#f5f7ff', 
                color: '#3e5bdb', 
                border: '1px solid #e3e7ff'
              }}
            >
              编辑资料
            </Button>
          </div>
        </div>

        {/* 详细信息两列布局 */}
        <div className="grid md:grid-cols-2 gap-10">
          <div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">姓名</div>
              <div className="text-gray-800">{me?.name || '-'}</div>
            </div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">邮箱</div>
              <div className="text-gray-800">{me?.email || '-'}</div>
            </div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">电话</div>
              <div className="text-gray-800">{me?.phone || '-'}</div>
            </div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">学院</div>
              <div className="text-gray-800">{me?.college || '-'}</div>
            </div>
          </div>
          <div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">工号</div>
              <div className="text-gray-800">{me?.account || '-'}</div>
            </div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">职称</div>
              <div className="text-gray-800">{me?.title || '-'}</div>
            </div>
            <div className="flex gap-4 mb-3">
              <div className="w-20 text-gray-500 text-sm">研究方向</div>
              <div className="text-gray-800">{me?.researchArea || '-'}</div>
            </div>
          </div>
        </div>
        
        {/* 简介 */}
        <div className="mt-4 pt-4 border-t border-gray-200">
          <div className="text-gray-500 text-sm mb-2">简介</div>
          <div className="text-gray-700 leading-relaxed">{me?.intro || '-'}</div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid md:grid-cols-2 gap-6">
        <Card 
          className="shadow-md hover:shadow-lg transition-shadow cursor-pointer"
          bordered={false}
          onClick={() => navigate('/teacher')}
        >
          <div className="flex items-center justify-between">
            <div>
              <div className="text-gray-500 text-sm mb-2">当前课程</div>
              <Statistic 
                value={myCourses.length} 
                suffix="门" 
                valueStyle={{ fontSize: '32px', fontWeight: 700, color: '#1890ff' }}
              />
            </div>
            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center">
              <BookOutlined className="text-3xl text-blue-500" />
            </div>
          </div>
        </Card>
        <Card 
          className="shadow-md hover:shadow-lg transition-shadow cursor-pointer"
          bordered={false}
          onClick={() => navigate('/teacher/apply')}
        >
          <div className="flex items-center justify-between">
            <div>
              <div className="text-gray-500 text-sm mb-2">申请中课程</div>
              <Statistic 
                value={appliedCourses.filter(c => c.status === 'pending').length} 
                suffix="门" 
                valueStyle={{ fontSize: '32px', fontWeight: 700, color: '#722ed1' }}
              />
            </div>
            <div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center">
              <FileTextOutlined className="text-3xl text-purple-500" />
            </div>
          </div>
        </Card>
      </div>

      {/* 安全设置 */}
      <Card 
        title={<span className="text-lg font-semibold text-gray-800">安全设置</span>}
        className="shadow-md"
        bordered={false}
      >
        <List
          itemLayout="horizontal"
          dataSource={[
            { 
              icon: <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                <SafetyOutlined className="text-blue-500 text-lg" />
              </div>, 
              title: '修改密码', 
              desc: '上次修改：30天前',
              onClick: () => {
                setIsPasswordModalOpen(true);
                passwordForm.resetFields();
              } 
            },
            { 
              icon: <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                <LogoutOutlined className="text-red-500 text-lg" />
              </div>, 
              title: '退出登录', 
              danger: true, 
              onClick: handleLogout
            },
          ]}
          renderItem={(item) => (
            <List.Item 
              onClick={item.onClick} 
              className="cursor-pointer hover:bg-gray-50 rounded-lg px-3 transition-colors"
            >
              <List.Item.Meta 
                avatar={item.icon} 
                title={
                  <span className={`text-base ${item.danger ? 'text-red-500 font-medium' : 'text-gray-800 font-medium'}`}>
                    {item.title}
                  </span>
                }
                description={item.desc && (
                  <span className="text-xs text-gray-400 mt-1 block">{item.desc}</span>
                )}
              />
              <RightOutlined className="text-gray-400" />
            </List.Item>
          )}
        />
      </Card>

      {/* 编辑资料Modal */}
      <Modal
        title="编辑资料"
        open={isEditModalOpen}
        onOk={handleSubmit}
        onCancel={() => {
          setIsEditModalOpen(false);
          form.resetFields();
        }}
        confirmLoading={updateProfileMutation.isPending}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          className="mt-4"
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          
          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
            
            <Form.Item
              label="电话"
              name="phone"
              rules={[
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
              ]}
            >
              <Input placeholder="请输入电话" />
            </Form.Item>
          </div>

          <Form.Item
            label="所属学院"
            name="college"
          >
            <Input placeholder="所属学院" disabled />
          </Form.Item>

          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="工号"
              name="account"
            >
              <Input placeholder="工号" disabled />
            </Form.Item>
            
            <Form.Item
              label="职称"
              name="title"
              rules={[{ required: true, message: '请输入职称' }]}
            >
              <Input placeholder="如：教授、副教授" />
            </Form.Item>
          </div>

          <Form.Item
            label="研究方向"
            name="researchArea"
          >
            <Input.TextArea 
              placeholder="请输入研究方向，多个方向用、分隔" 
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码Modal */}
      <Modal
        title="修改密码"
        open={isPasswordModalOpen}
        onCancel={() => {
          setIsPasswordModalOpen(false);
          passwordForm.resetFields();
        }}
        onOk={() => {
          passwordForm.submit();
        }}
        confirmLoading={changePasswordMutation.isPending}
        okText="确认修改"
        cancelText="取消"
        width={500}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          className="mt-4"
          onFinish={(values) => {
            changePasswordMutation.mutate({
              oldPassword: values.oldPassword,
              newPassword: values.newPassword,
            });
          }}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password placeholder="请输入当前密码" />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少为6位' },
            ]}
          >
            <Input.Password placeholder="请输入新密码（至少6位）" />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

